package com.tang.nacos.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


/**
 * mybatis sharding配置
 */
@Configuration
@MapperScan(basePackages = "com.tang.nacos.shardingdao", sqlSessionTemplateRef = "ds2SqlSessionTemplate")
public class MybatisShardingConfig {


  // 主数据源 ds2数据源
  @Bean("ds2SqlSessionFactory")
  public SqlSessionFactory ds1SqlSessionFactory(
      @Qualifier("shardingDateSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    sqlSessionFactory.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
    return sqlSessionFactory.getObject();
  }

  @Bean(name = "ds2TransactionManager")
  public DataSourceTransactionManager ds1TransactionManager(
      @Qualifier("shardingDateSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "ds2SqlSessionTemplate")
  public SqlSessionTemplate ds1SqlSessionTemplate(
      @Qualifier("ds2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }


}
